//
//  UIButton+XG.m
//  Project
//
//  Created by sins on 16/7/11.
//  Copyright © 2018 益萃网络科技（中国）有限公司. All rights reserved.
//

#import "UIButton+BZ.h"
#import <objc/runtime.h>
#import "UIButton+WebCache.h"

static const void *associatedKey       = "btnAssociatedKey";
static const void *associatedReturnKey = "btnAssociatedKeyReturn";

@implementation UIButton (XG)

- (void)setClick:(Click)click {

    objc_setAssociatedObject(self, associatedKey, click, OBJC_ASSOCIATION_COPY_NONATOMIC);

    [self removeTarget:self
                  action:@selector(buttonClick)
        forControlEvents:UIControlEventTouchUpInside];

    if (click) {

        [self addTarget:self
                      action:@selector(buttonClick)
            forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)setClickReturn:(ClickReturn)clickReturn {
    objc_setAssociatedObject(self, associatedReturnKey, clickReturn,
                             OBJC_ASSOCIATION_COPY_NONATOMIC);

    [self removeTarget:self
                  action:@selector(buttonReturnClick:)
        forControlEvents:UIControlEventTouchUpInside];
    if (clickReturn) {
        [self addTarget:self
                      action:@selector(buttonReturnClick:)
            forControlEvents:UIControlEventTouchUpInside];
    }
}

- (Click)click {

    return objc_getAssociatedObject(self, associatedKey);
}

- (ClickReturn)clickReturn {
    return objc_getAssociatedObject(self, associatedReturnKey);
}

- (void)buttonClick {

    if (self.click) { self.click(); }
}

- (void)buttonReturnClick:(UIButton *)btn {
    if (self.clickReturn) { self.clickReturn(btn); }
}

- (void)setBtnImageWithImageType:(XGSetBtnImageType)imageType
                        forState:(UIControlState)state
                        ImageURL:(NSString *)urlStr
                PlaceholderImage:(NSString *)imageStr {
    
    // 如果没设置图片,使用系统默认图片
    if (imageStr == nil || [imageStr isEqualToString:@""]) { imageStr = @"Default.png"; }
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    UIImage *image = [UIImage imageNamed:imageStr];
    
    switch (imageType) {
        case XGSetBtnImage:
            [self sd_setImageWithURL:url forState:state placeholderImage:image];
            break;
        case XGSetBackIamge:
            [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:image];
            break;
    }
}

@end
